const router = require('koa-router')()
const axios = require('axios')

router.post('/login', async (ctx, next) => {
  const code = ctx.request.body.code
  const res = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?appid=修改为自己的APPID&secret=修改为自己的密钥&js_code=${code}&grant_type=authorization_code`)
  const { session_key, unionid, errmsg, openid, errcode } = res.data
  ctx.body = { openid }
})

router.post('/subscribe', async (ctx, next) => {
  console.log('订阅')
  let now = new Date().getTime();
  if (!ctx.state.accessToken || (ctx.state.t != null && ctx.state.t - now < 5 * 60 * 1000)) {
    const res = await axios.get(`https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=修改为自己的APPID&secret=修改为自己的密钥`)
    console.log(res)
    const { access_token } = res.data
    if (access_token != null) {
      ctx.state.t = now
      ctx.state.accessToken = access_token
    } else {
      ctx.body = {
        code: 999
      }
      return
    }
  }
  console.log('发送消息')
  axios.post(`https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=${ctx.state.accessToken}`, {
    template_id: '修改为自己的消息模板',
    touser: ctx.request.body.openid,
    data: {
      name3: {
        value: '测试'
      },
      thing1: {
        value: '测试'
      }
    },
    miniprogram_state: 'developer',
    lang: 'zh_CN'
  })
  ctx.body = {
    code: 0
  }
})

module.exports = router
